package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
        @GetMapping("/page")
        public R<Page> page(int page,int pageSize){
            Page pageinfo = new Page<>(page,pageSize);
            //LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            categoryService.page(pageinfo);

            return  R.success(pageinfo);
        }

    /**
     * 新增菜品
     * @param request
     * @param category
     * @return
     */
        @PostMapping()
        public R<String> save(HttpServletRequest request, @RequestBody Category category){
//            Long cgId= (Long) request.getSession().getAttribute("employee");
//            category.setCreateTime(LocalDateTime.now());
//            category.setUpdateTime(LocalDateTime.now());
//            category.setCreateUser(cgId);
//            category.setUpdateUser(cgId);
            categoryService.save(category);
            return R.success("添加成功");
        }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping()
        public R<String> delete(Long ids){
            //log.info("sdfsadf"+ids);
            //categoryService.removeById(ids);
            categoryService.remove(ids);
            return R.success("删除成功");
        }

    /**
     * 添加
     * @param request
     * @param category
     * @return
     */
    @PutMapping()
    public R<String> update(HttpServletRequest request, @RequestBody Category category){
        Long cgId= (Long) request.getSession().getAttribute("employee");
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(cgId);
        category.setUpdateUser(cgId);
        categoryService.updateById(category);
        return R.success("添加成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
